package com.xh.bussiness.exam.controller;

import com.xh.bussiness.exam.bean.request.UserErrorQuestionRequest;
import com.xh.bussiness.exam.bean.request.UserErrorQuestionSaveRequest;
import com.xh.bussiness.exam.model.UserErrorQuestion;
import com.xh.bussiness.exam.service.IUserErrorQuestionService;
import com.xh.bussiness.jingyou.service.IJYQuestionService;
import com.xh.bussiness.tiku.bean.dto.QuestionDto;
import com.xh.bussiness.tiku.bean.request.QuestionSaveRequest;
import com.xh.bussiness.tiku.model.Question;
import com.xh.bussiness.tiku.service.IQuestionService;
import com.xh.core.bean.AjaxResult;
import com.xh.core.bean.XhExportHeaderBean;
import com.xh.core.bean.XhPage;
import com.xh.core.constant.AjaxResultConstant;
import com.xh.core.controller.BaseController;
import com.xh.core.util.StringUtils;
import com.xh.core.util.UserUtils;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;


/**
 * <p>
 * 用户错题本 前端控制器
 * </p>
 *
 * @author JQM
 * @since 2019-11-04
 */
@Api(tags = "学生错题相关接口")
@RestController
@RequestMapping("/admin/userErrorQuestion")
public class UserErrorQuestionController extends BaseController {

    Logger log = LoggerFactory.getLogger(UserErrorQuestionController.class);

    @Autowired
    private IUserErrorQuestionService userErrorQuestionService;
    @Autowired
    private IQuestionService questionService;

    /**
     * 分页数据查询
     *
     * @param page 分页对象
     * @param bean 查询条件Bean
     * @return
     */
    @ApiOperation("分页查询学生的错题")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "学生ID", dataType = "String", required = true),
    })
    @PostMapping("/queryPage")
    public AjaxResult queryPage(@RequestBody UserErrorQuestionRequest bean) {
        XhPage page = new XhPage();
        page.setCurrent(bean.getCurrent());
        page.setSize(bean.getSize());


        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, userErrorQuestionService.queryUserErrorQuestionPage(page, bean));
    }

    /**
     * 数据查询
     *
     * @param bean 查询条件Bean
     * @return
     */
    @PostMapping("/query")
    public AjaxResult query(UserErrorQuestionRequest bean) {
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, "", userErrorQuestionService.queryUserErrorQuestion(bean));
    }

    /**
     * 导出全部
     *
     * @param bean
     * @return
     */
    @PostMapping(value = "/exportAll")
    public AjaxResult exportAll(UserErrorQuestionRequest bean, HttpServletRequest request) {
        try {
            LinkedHashMap<String, XhExportHeaderBean> exportHeaderBeans = new LinkedHashMap<>();
            //exportHeaderBeans.put("username",new XhExportHeaderBean("用户名"));
            //exportHeaderBeans.put("deleted",new XhExportHeaderBean("是否删除",ImmutableMap.of(0,"否",1,"是")));
            //exportHeaderBeans.put("createTime",new XhExportHeaderBean("创建时间","yyyy-MM-dd HH:mm:ss"));

            String downloadUrl = userErrorQuestionService.exportAll(request, exportHeaderBeans, bean, "queryUserErrorQuestionPage");
            if (downloadUrl != null) {
                return new AjaxResult(AjaxResultConstant.Result.SUCCESS, "", downloadUrl);
            } else {
                return new AjaxResult(AjaxResultConstant.Result.ERROR, "导出失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(AjaxResultConstant.Result.ERROR);
        }
    }

    /**
     * 新增和保存
     *
     * @param userErrorQuestion 实体对象
     * @return
     */
    @PostMapping(value = "/saveOrUpdate")
    @Transactional
    public AjaxResult saveOrUpdate(@Validated UserErrorQuestion userErrorQuestion) {
        if (userErrorQuestion.getId() == null) {
            userErrorQuestionService.insert(userErrorQuestion);
        } else {
            userErrorQuestionService.update(userErrorQuestion);
        }
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS);
    }

    /**
     * 删除操作
     *
     * @param id
     * @return
     */
    @PostMapping("/deleteById/{id}")
    @Transactional
    public AjaxResult deleteById(@PathVariable String id) {
        userErrorQuestionService.delete(id);
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS);
    }

    /**
     * 批量删除操作
     *
     * @param ids
     * @return
     */
    @PostMapping("/batchDelete")
    @Transactional
    public AjaxResult batchDelete(String[] ids) {
        userErrorQuestionService.batchDelete(ids);
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS);
    }

    /**
     * 查询每个学科的错题数
     *
     * @return
     */
    @PostMapping("/queryCountBySubject")
    @ApiOperation("查询每个学科的错题数")
    public AjaxResult queryCountBySubject(String studentId) {
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, userErrorQuestionService.queryCountBySubject(studentId));
    }

    @ApiOperation("根据日历查询学生错题数")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "studentId", value = "学生ID", required = true),
            @ApiImplicitParam(name = "year", value = "年份"),
            @ApiImplicitParam(name = "year", value = "月份")
    })
    @RequestMapping("/queryCountByCalendar")
    public AjaxResult queryCountByCalendar(String studentId, Integer year, Integer month) {
        if (StringUtils.isEmpty(studentId)) {
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "参数错误");
        }
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, userErrorQuestionService.queryCountByCalendar(studentId, year, month));
    }

    @ApiOperation("根据日期查询错题")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "studentId", value = "学生ID", required = true),
            @ApiImplicitParam(name = "date", value = "查询日期 格式：[yyyy-MM-dd]")
    })
    @RequestMapping("/queryStuErrorQuestionIdByDate")
    public AjaxResult queryStuErrorQuestionIdByDate(XhPage page, String studentId, String date) {
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, userErrorQuestionService.queryStuErrorQuestionIdByDate(page, studentId, date));
    }

    @ApiOperation("查看学生错题详情")
    @ApiImplicitParam(name = "errorQuestionId", value = "学生错题ID")
    @RequestMapping("/queryUserErrorQuestionDetail")
    public AjaxResult queryUserErrorQuestionDetail(String errorQuestionId) {
        if (StringUtils.isEmpty(errorQuestionId)) {
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "参数错误");
        }
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, userErrorQuestionService.queryUserErrorQuestionDetail(errorQuestionId));
    }

    /**
     * 新增和保存
     *
     * @param bean 实体对象
     * @return
     * @throws Exception
     */
    @ApiOperation("保存学生错题")
    @PostMapping(value = "/addUserErrorQuestion")
    @Transactional
    public AjaxResult addUserErrorQuestion(@Validated @RequestBody UserErrorQuestionSaveRequest bean) throws Exception {
        // 判断试题是否存在试题库中
    	/*String imgPath = "upload"+ bean.getImgPath().split("upload")[1];
    	bean.setImgPath(imgPath);
        if (bean.getQuestion() != null) {
            //更新学科
            if (StringUtils.isEmpty(bean.getSubjectId())) {
                bean.getQuestion().setSubjectId(bean.getSubjectId());
            }
            QuestionDto questionDto = questionService.addQuestion(bean.getQuestion());
            bean.setQuestionId(questionDto.getId());
        }*/

        if (1 == bean.getContentType()) {
            if (bean.getQuestion() == null) {
                return new AjaxResult(AjaxResultConstant.Result.ERROR, "试题不存在");
            }
            String imgPath = "upload" + bean.getImgPath().split("upload")[1];
            QuestionDto question = bean.getQuestion();
            QuestionDto detail = questionService.addQuestion(question);
            detail.setImgPath(imgPath);
            detail.setContentType(bean.getContentType());
            questionService.addQuestion(detail);
            bean.setQuestionId(detail.getId());
            bean.setQuestionVersion(detail.getCurrentVersion());
        } else {
            String imgPath = "upload" + bean.getImgPath().split("upload")[1];
            QuestionSaveRequest questionBean = new QuestionSaveRequest();
            questionBean.setType(bean.getQuestion().getType());
            questionBean.setContentType(bean.getContentType());
            questionBean.setSubjectId(bean.getSubjectId());
            questionBean.setTitle(bean.getQuestion().getTitle());
            questionBean.setImgPath(imgPath);
            QuestionDto question = questionService.addQuestion(questionBean);
            bean.setQuestionId(question.getId());
            bean.setQuestionVersion(question.getCurrentVersion());
        }
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, userErrorQuestionService.addUserErrorQuestion(bean));
    }
    /**
     * @param id
     * @param page
     * @return
     */
    @ApiOperation("根据试卷id查询")
    @ApiImplicitParams({
    	 	@ApiImplicitParam(name = "studentId", value = "学生ID", dataType = "String", required = true),
            @ApiImplicitParam(name = "paperId", value = "错题试卷id", dataType = "String", required = true),
            @ApiImplicitParam(name = "current", value = "当前页数", dataType = "int", required = true),
            @ApiImplicitParam(name = "size", value = "每页条数", dataType = "int", required = true),
    })
    @PostMapping("/queryByPaperId")	
    public AjaxResult queryByPaperId(String studentId ,String paperId, XhPage page) {
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, userErrorQuestionService.queryByPaperId(page, paperId, studentId));
    }

    @RequestMapping("/checkUserErrorQuestion")
    public AjaxResult checkUserErrorQuestion(@RequestBody UserErrorQuestionRequest request) {
        if (StringUtils.isEmpty(request.getStudentId()) || request.getQuestionDto() == null) {
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "参数错误");
        }
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, userErrorQuestionService.checkUserErrorQuestion(request));
    }

    @RequestMapping("/cancelUserErrorQuestion")
    public AjaxResult cancelUserErrorQuestion(String[] ids) {
        if (ids != null && ids.length > 0) {
            userErrorQuestionService.cancelUserErrorQuestion(ids);
            return new AjaxResult(AjaxResultConstant.Result.SUCCESS, "成功从错题本中移出");
        }else{
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "参数错误");
        }
    }


    /**
     * 按班级或学生查询错题
     * @author 赵文博
     * @date 2021/5/14 10:39
     * @param bean
     * @return com.xh.core.bean.AjaxResult
     **/
    @PostMapping("/queryPagePC")
    public AjaxResult queryPagePC(@RequestBody UserErrorQuestionRequest bean){
        XhPage page = new XhPage();
        page.setCurrent(bean.getCurrent());
        page.setSize(bean.getSize());
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS,userErrorQuestionService.queryErrorQuestion(page,bean));
    }

    /**
     * 查询错误学生
     * @author 赵文博
     * @date 2021/5/14 10:46
     * @param bean
     * @return com.xh.core.bean.AjaxResult
     **/
    @PostMapping("/queryErrorStudent")
    public AjaxResult queryErrorStudent(@RequestBody UserErrorQuestionRequest bean){
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS,userErrorQuestionService.queryErrorStudent(bean));
    }

}

